<template>
  <div class="bonus-compare">
    <h1 class="text-2xl font-bold mb-6">奖金比较系统</h1>
    
    <!-- 用户信息输入表单 -->
    <div v-if="!currentUser" class="mb-8">
      <h2 class="text-xl font-semibold mb-4">输入您的信息</h2>
      <form @submit.prevent="submitUserInfo" class="space-y-6">
        <div>
          <label class="block text-sm font-medium mb-1">姓名</label>
          <input
            v-model="userForm.name"
            type="text"
            required
            class="w-full px-3 py-2 border rounded-md"
            :class="{ 'border-red-500': nameError }"
          />
          <p v-if="nameError" class="text-red-500 text-sm mt-1">{{ nameError }}</p>
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">奖金数额</label>
          <input
            v-model.number="userForm.bonus"
            type="number"
            required
            min="0"
            class="w-full px-3 py-2 border rounded-md"
          />
        </div>
        <button
          type="submit"
          class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 mt-4"
        >
          提交
        </button>
      </form>
    </div>

    <!-- 奖金比较功能 -->
    <div v-else class="space-y-8">
      <!-- 比较功能 -->
      <div class="mb-8 p-8 bg-white rounded-lg shadow-sm">
        <h2 class="text-xl font-semibold mb-8 text-gray-800">奖金比较</h2>
        <div class="space-y-8">
          <div class="flex items-center justify-between gap-8">
            <div class="flex-1">
              <div class="text-sm text-gray-500 mb-2">当前用户</div>
              <div class="px-4 py-3 bg-blue-50 border border-blue-100 rounded-lg text-blue-700 font-medium">
                {{ currentUser.name }}
              </div>
            </div>
            <div class="flex-1">
              <div class="text-sm text-gray-500 mb-2">选择比较对象</div>
              <select
                v-model="compareForm.user2"
                class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">请选择要比较的用户</option>
                <option
                  v-for="user in otherUsers"
                  :key="user.name"
                  :value="user.name"
                >
                  {{ user.name }}
                </option>
              </select>
            </div>
          </div>
          <div class="flex justify-center">
            <button
              @click="compareBonus"
              :disabled="!compareForm.user2"
              class="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors duration-200"
            >
              比较奖金
            </button>
          </div>
          <div v-if="compareResult" class="mt-6 p-4 bg-gray-50 rounded-lg">
            <p class="text-lg font-medium text-gray-800 text-center">
              {{ compareResult }}
            </p>
          </div>
        </div>
      </div>

      <!-- 相似奖金查询 -->
      <div class="p-6 bg-white rounded-lg shadow-sm">
        <h2 class="text-xl font-semibold mb-6 text-gray-800">查询相似奖金</h2>
        <div class="space-y-6">
          <div>
            <label class="block text-sm text-gray-500 mb-2">最大差值</label>
            <input
              v-model.number="similarForm.maxDiff"
              type="number"
              min="100"
              step="100"
              class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
            <p class="text-sm text-gray-500 mt-1">请输入100的倍数</p>
          </div>
          <button
            @click="findSimilarBonus"
            :disabled="!similarForm.maxDiff || similarForm.maxDiff % 100 !== 0"
            class="bg-purple-500 text-white px-4 py-2 rounded-md hover:bg-purple-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors duration-200"
          >
            查询
          </button>
          <div v-if="similarUsers.length > 0" class="mt-6">
            <h3 class="text-lg font-medium text-gray-800 mb-4">相似奖金用户：</h3>
            <ul class="space-y-3">
              <li
                v-for="user in similarUsers"
                :key="user.name"
                class="p-4 bg-gray-50 rounded-lg border border-gray-100 hover:bg-gray-100 transition-colors duration-200"
              >
                {{ user.name }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useFHE } from '../composables/useFHE'

const { encrypt, decrypt, compare, getAllUsers, addUser, isNameExists } = useFHE()

// 用户数据存储
const users = ref([])
const currentUser = ref(null)
const nameError = ref('')

// 表单数据
const userForm = ref({
  name: '',
  bonus: null
})

const compareForm = ref({
  user2: ''
})

const similarForm = ref({
  maxDiff: 100
})

// 比较结果
const compareResult = ref('')
const similarUsers = ref([])

// 获取所有用户列表（去重）
const allUsers = computed(() => {
  const uniqueUsers = new Map()
  users.value.forEach(user => {
    if (!uniqueUsers.has(user.name)) {
      uniqueUsers.set(user.name, user)
    }
  })
  return Array.from(uniqueUsers.values())
})

// 获取除当前用户外的其他用户列表（确保不重复）
const otherUsers = computed(() => {
  const uniqueUsers = new Map()
  users.value.forEach(user => {
    if (user.name !== currentUser.value?.name && !uniqueUsers.has(user.name)) {
      uniqueUsers.set(user.name, user)
    }
  })
  return Array.from(uniqueUsers.values())
})

// 初始化时加载用户数据
onMounted(() => {
  users.value = getAllUsers()
})

// 提交用户信息
const submitUserInfo = () => {
  // 检查用户名是否存在
  const existingUser = users.value.find(user => user.name === userForm.value.name)
  
  if (existingUser) {
    // 如果用户存在，验证奖金是否匹配
    if (existingUser.bonus !== userForm.value.bonus) {
      nameError.value = '奖金数额与记录不符'
      return
    }
    // 奖金匹配，直接使用现有用户数据
    currentUser.value = existingUser
  } else {
    // 新用户，创建并保存
    nameError.value = ''
    const newUser = {
      name: userForm.value.name,
      bonus: userForm.value.bonus,
      encryptedBonus: encrypt(userForm.value.bonus)
    }
    
    users.value.push(newUser)
    addUser(newUser)
    currentUser.value = newUser
  }
  
  // 重置表单
  userForm.value = {
    name: '',
    bonus: null
  }
}

// 比较奖金
const compareBonus = () => {
  const user2 = users.value.find(u => u.name === compareForm.value.user2)
  
  if (!user2) return
  
  const result = compare(currentUser.value.encryptedBonus, user2.encryptedBonus)
  compareResult.value = `${currentUser.value.name}的奖金${result > 0 ? '>' : result < 0 ? '<' : '='}${user2.name}的奖金`
}

// 查找相似奖金
const findSimilarBonus = () => {
  if (!currentUser.value || !similarForm.value.maxDiff) return
  
  // 确保最大差值是100的倍数
  if (similarForm.value.maxDiff % 100 !== 0) {
    return
  }
  
  const currentBonus = currentUser.value.bonus
  const uniqueUsers = new Map()
  
  users.value.forEach(user => {
    if (user.name !== currentUser.value.name) {
      const diff = Math.abs(user.bonus - currentBonus)
      if (diff <= similarForm.value.maxDiff) {
        uniqueUsers.set(user.name, user)
      }
    }
  })
  
  similarUsers.value = Array.from(uniqueUsers.values())
    .sort((a, b) => Math.abs(a.bonus - currentBonus) - Math.abs(b.bonus - currentBonus))
}
</script>

<style scoped>
.bonus-compare {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

.space-y-6 > * + * {
  margin-top: 1.5rem;
}

/* 添加输入框和按钮的过渡效果 */
input, select, button {
  transition: all 0.2s ease-in-out;
}

/* 添加hover效果 */
button:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style> 